package com.example.demo.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.demo.Mapper.ProductInfoMapper;
import com.example.demo.Mapper.ProductLogMapper;
import com.example.demo.base.ArrayCountUtils;
import com.example.demo.base.Result;
import com.example.demo.entity.ProductInfo;
import com.example.demo.entity.ProductLog;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.demo.Mapper.AgriProductMapper;
import com.example.demo.base.Result;
import com.example.demo.entity.AgriProduct;
import com.example.demo.entity.Commodity;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

import static com.example.demo.base.ArrayCountUtils.merge;
import static com.example.demo.base.ArrayCountUtils.subDouble;

@RestController
//@MapperScan("com.example.demo.Mapper")
@RequestMapping("/productLog")
//@MapperScan("com.example.demo.Mapper")
public class ProductLogController {
    @Resource
    ProductLogMapper productLogMapper;//ProductLog
    @Resource
    ProductInfoMapper productInfoMapper;//ProductInfo

    /**
     * 获取数据库全部信息
     *
     * @return
     */
    @GetMapping("/all")
    public Result<?> findAll() {
        return Result.success(productLogMapper.selectList(null));
    }

    /**
     * 获取产品物流重量表并去重
     *
     * @return
     */
    @GetMapping("/chatData")
    public Result<?> chatData(@RequestParam int tenantId) {
        LambdaQueryWrapper<ProductLog> queryWrapper = new LambdaQueryWrapper<>();
        //筛选出ProductLog表中tenantId和传递过来的数值相等的记录。
        queryWrapper.eq(ProductLog::getTenantId, tenantId);
        List<ProductLog> productLogList = productLogMapper.selectList(queryWrapper);
        List<ArrayCountUtils.BillsNums> billsNumsList = new ArrayList<>();
        for (ProductLog log : productLogList) {
            ArrayCountUtils.BillsNums billsNums = new ArrayCountUtils.BillsNums();
            billsNums.setId(log.getProductName());
            billsNums.setSums(log.getProductWeight());
            billsNumsList.add(billsNums);
            billsNums = null;// 置空强制回收内存，以防数据量大内存泄露
        }
        List<ArrayCountUtils.BillsNums> res = merge(billsNumsList);
        return Result.success(res);
    }

    /**
     * 分页获取数据库数据
     *
     * @param pageNum
     * @param pageSize
     * @return
     */
    @GetMapping(value = "/pageAll")
    public Result<?> findPagePL(@RequestParam(defaultValue = "1") Integer pageNum,
                                @RequestParam(defaultValue = "10") Integer pageSize,
                                @RequestParam String tenantId) {
        LambdaQueryWrapper<ProductLog> wrapper = Wrappers.<ProductLog>lambdaQuery();
        wrapper.eq(ProductLog::getTenantId, Integer.valueOf(tenantId));
        Page<ProductLog> farmInfoPage = productLogMapper.selectPage(new Page<>(pageNum, pageSize), wrapper);
        return Result.success(farmInfoPage);
    }

    /*
     */

    /**
     * 根据productCode精确查询
     *
     * @return
     */
    @GetMapping("/findByCode")
    public Result<?> findByproductCodeAndTenantId(@RequestParam String productCode, @RequestParam String tenantId) {
        ProductLog productLog = productLogMapper.selectOne(new QueryWrapper<ProductLog>().eq("product_Code", productCode).eq("tenant_id", tenantId));
        List<ProductLog> productLogList = new ArrayList<>();
        if (productLog != null) {
            productLogList.add(productLog);
            return Result.success(productLogList);
        }
        return Result.error(0, "没有查询到相关数据");
    }

    @GetMapping("/findOnes")
    public Result<?> findOnes(@RequestParam String productId) {
        LambdaQueryWrapper<ProductLog> wrapper = Wrappers.<ProductLog>lambdaQuery();
        wrapper.eq(ProductLog::getProductId, Integer.valueOf(productId));
        List<ProductLog> productLogList = productLogMapper.selectList(wrapper);
        if (productLogList.size()>0) {
            return Result.success(productLogList);
        }
        return Result.error(0, "没有查询到相关产品出库物流信息");
    }


    /**
     * 根据productName模糊查询
     *
     * @param productName
     * @return
     */
    @GetMapping("/findByProductName")
    public Result<?> findByProductName(@RequestParam(defaultValue = "1") Integer pageNum,
                                       @RequestParam(defaultValue = "10") Integer pageSize,
                                       @RequestParam String productName,
                                       @RequestParam String tenantId) {
        // 构建查询条件
        QueryWrapper<ProductLog> wrapper = new QueryWrapper<>();
        wrapper.like("product_name", productName);
        wrapper.eq("tenant_id", tenantId);
        // 执行查询，并返回查询结果
        Page<ProductLog> productLogList = productLogMapper.selectPage(new Page<>(pageNum, pageSize), wrapper);
        if (productLogList.getTotal() > 0) {
            return Result.success(productLogList);
        } else {
            return Result.error(0, "没有查询到相关数据");
        }
    }

    @DeleteMapping("/delById")
    public Result<?> delete(@RequestParam String productCode,
                            @RequestParam String tenantId) {
        ProductLog productLog = new ProductLog();
        productLog.setProductCode(productCode);
        productLog.setTenantId(Integer.valueOf(tenantId));
        int res = productLogMapper.deleteByMultiId(productLog);
        if (res > 0)
            return Result.success();
        return Result.error(0, "删除失败");
    }

    /**
     * 添加信息
     *
     * @param productName
     * @param productId
     * @param productCode
     * @param productWeight
     * @param productSource
     * @param outCharge
     * @param destination
     * @param inCharge
     * @param productBirth
     * @param transporter
     * @param note
     * @return
     */

    @GetMapping(value = "/add")
    public Result<?> saveP(@RequestParam String productName,
                           @RequestParam String productId,
                           @RequestParam String productCode,
                           @RequestParam String productWeight,
                           @RequestParam String productSource,
                           @RequestParam String outCharge,
                           @RequestParam String destination,
                           @RequestParam String inCharge,
                           @RequestParam String productBirth,
                           @RequestParam String expiration,
                           @RequestParam String transporter,
                           @RequestParam String note,
                           @RequestParam String tenantId // 新增参数
    ) {
        // 参数校验
        if (expiration.isEmpty() || productName.isEmpty() || productId.isEmpty()
                || productCode.isEmpty() || productWeight.isEmpty()
                || productSource.isEmpty() || outCharge.isEmpty()
                || destination.isEmpty() || inCharge.isEmpty()
                || productBirth.isEmpty() || transporter.isEmpty()) {
            return Result.error(0, "请填写完整信息");
        }
        // TOD:获取产品信息
        ProductInfo productInfo = new ProductInfo();
        productInfo.setComId(Integer.valueOf(productId));
        productInfo.setTenantId(Integer.valueOf(tenantId));
        ProductInfo tmp = productInfoMapper.selectByMultiId(productInfo);

        // TOD:添加物流信息
        ProductLog productLog = new ProductLog();
        productLog.setProductName(productName);
        productLog.setProductId(Integer.valueOf(productId));
        productLog.setProductCode(productCode);
        productLog.setProductWeight(Double.valueOf(productWeight));
        productLog.setProductSource(productSource);
        productLog.setOutCharge(outCharge);
        productLog.setDestination(destination);
        productLog.setInCharge(inCharge);
        productLog.setProductBirth(productBirth);
        productLog.setExpiration(expiration);
        productLog.setTransporter(transporter);
        productLog.setNote(note);
        productLog.setTenantId(Integer.valueOf(tenantId)); // 设置 tenantId

        // TOD:计算库存信息
        double w =  subDouble(tmp.getWeight(), Double.valueOf(productWeight));

        // TOD:更新产品库存信息
        ProductInfo t = new ProductInfo(Integer.valueOf(productId), productName, w, productBirth, expiration, note, Integer.valueOf(tenantId));
        productInfoMapper.updateByMultiId(t);

        // TOD:更新物流信息
        productLogMapper.insert(productLog);
        return Result.success();
    }

    /**
     * 根据code更新数据
     *
     * @param productName
     * @param productId
     * @param productCode
     * @param productWeight
     * @param productSource
     * @param outCharge
     * @param destination
     * @param inCharge
     * @param productBirth
     * @param transporter
     * @param note
     * @return
     */
    @GetMapping(value = "/update")
    public Result<?> updateById(@RequestParam String productName,
                                @RequestParam String productId,
                                @RequestParam String productCode,
                                @RequestParam String productWeight,
                                @RequestParam String productSource,
                                @RequestParam String outCharge,
                                @RequestParam String destination,
                                @RequestParam String inCharge,
                                @RequestParam String productBirth,
                                @RequestParam String expiration,
                                @RequestParam String transporter,
                                @RequestParam String note,
                                @RequestParam String tenantId
    ) {
        if (expiration.isEmpty() || productName.isEmpty() || productId.isEmpty() || productCode.isEmpty() || productWeight.isEmpty() || productSource.isEmpty() || outCharge.isEmpty() || destination.isEmpty() || inCharge.isEmpty() || productBirth.isEmpty() || transporter.isEmpty()) {
            return Result.error(0, "请填写完整信息");
        }
        ProductLog productLog = new ProductLog();
        productLog.setProductName(productName);
        productLog.setProductId(Integer.valueOf(productId));
        productLog.setProductCode(productCode);
        productLog.setProductWeight(Double.valueOf(productWeight));
        productLog.setProductSource(productSource);
        productLog.setOutCharge(outCharge);
        productLog.setDestination(destination);
        productLog.setInCharge(inCharge);
        productLog.setProductBirth(productBirth);
        productLog.setExpiration(expiration);
        productLog.setTransporter(transporter);
        productLog.setNote(note);
        productLog.setTenantId(Integer.valueOf(tenantId));
        productLogMapper.updateByMultiId(productLog);
        return Result.success();
    }

}

